package permission

import (
	"gin_management_system/middleware/inject"
	jwtGet "gin_management_system/pkg/util"
	"github.com/gin-gonic/gin"
	"net/http"
)

func CasbinMiddleware(c *gin.Context) {
	Authorization := c.GetHeader("Authorization")
	claims, _ := jwtGet.ParseToken(Authorization)
	if claims == nil {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "Unauthorized",
			"data":    "",
		})
		c.Abort()
		return
	}
	res, err := inject.Obj.Enforcer.EnforceSafe(claims.Username, c.Request.URL.Path, c.Request.Method)
	// 这个 HasPermissionForUser 跟上面的有什么区别
	// EnforceSafe 会验证角色的相关的权限
	// 而 HasPermissionForUser 只验证用户是否有权限
	//res = Enforcer.HasPermissionForUser(userName,p,m)
	if err != nil {
		//fmt.Println("no permission ")
		//fmt.Println(err)
		c.JSON(200, gin.H{
			"code":    401,
			"message": "Unauthorized",
			"data":    "",
		})
		c.Abort()
		return
	}
	if !res {
		//fmt.Println("permission check failed")
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "Unauthorized",
			"data":    "",
		})
		c.Abort()
		return
	}
	c.Next()
}